<template>
  <div class="login-container">
    <div class="login-left">
      <slogan class="left-icon"></slogan>
      <div class="left-title">初遇后台管理系统</div>
    </div>
    <div class="login-right">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
        <div class="title-container">
          <div class="c-title">嗨！欢迎回来！</div>
          <div class="c-dection">请输入您的账户信息开始管理您的项目</div>
        </div>
        <div class="right-main">
          <el-form-item prop="username">
            <!-- <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input ref="username" v-model="loginForm.username" placeholder="Username" name="username" type="text" tabindex="1" autocomplete="on" /> -->
            <el-input v-model="loginForm.username" size="large" placeholder="请输入用户名" prefix-icon="user" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input :key="passwordType" ref="password" size="large" v-model="loginForm.password" :type="passwordType" placeholder="Password" name="password" tabindex="2" autocomplete="on" @keyup="checkCapslock" @blur="capsTooltip = false" @keyup.enter="handleLogin" prefix-icon="Lock" />
            <!-- <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span> -->
          </el-form-item>

          <el-button :loading="loading" type="primary" size="large" style="width: 100%; margin-bottom: 30px" @click.prevent="handleLogin">登录</el-button>

          <div class="copy">Copyright © 2024</div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
  import { validUsername } from '@/utils/validate';
  import { defineComponent } from 'vue';
  import SocialSign from './components/SocialSignin.vue';
  import slogan from './components/slogan.vue';
  import type { FormItemRule } from 'element-plus';
  import type { IForm } from '@/types/element-plus';
  import store from '@/store';

  interface QueryType {
    // 自定义key 任意字符串
    [propname: string]: string;
  }

  export default defineComponent({
    name: 'Login',
    components: { SocialSign, slogan },
    data() {
      const validateUsername: FormItemRule['validator'] = (_rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('请输入用户名'));
        } else {
          callback();
        }
      };
      const validatePassword: FormItemRule['validator'] = (_rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('The password can not be less than 6 digits'));
        } else {
          callback();
        }
      };
      return {
        loginForm: {
          username: '',
          password: ''
        },
        loginRules: {
          username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        },
        passwordType: 'password',
        capsTooltip: false,
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {}
      };
    },
    watch: {
      $route: {
        handler: function (route) {
          const query = route.query;
          if (query) {
            this.redirect = query.redirect;
            this.otherQuery = this.getOtherQuery(query);
          }
        },
        immediate: true
      }
    },
    created() {
      // window.addEventListener('storage', this.afterQRScan)
    },
    mounted() {
      if (this.loginForm.username === '') {
        (this.$refs.username as HTMLElement).focus();
      } else if (this.loginForm.password === '') {
        (this.$refs.password as HTMLElement).focus();
      }
    },
    unmounted() {
      // window.removeEventListener('storage', this.afterQRScan)
    },
    methods: {
      checkCapslock(e) {
        const { key } = e;
        this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z';
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = '';
        } else {
          this.passwordType = 'password';
        }
        this.$nextTick(() => {
          (this.$refs.password as HTMLElement).focus();
        });
      },
      handleLogin() {
        (this.$refs.loginForm as IForm).validate(valid => {
          return new Promise((resolve, reject) => {
            if (valid) {
              this.loading = true;
              store
                .user()
                .login(this.loginForm)
                .then(() => {
                  this.$router.push({ path: this.redirect || '/', query: this.otherQuery });
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                })
                .finally(() => {
                  resolve();
                });
            } else {
              console.log('error submit!!');
              reject();
            }
          });
        });
      },
      getOtherQuery(query: QueryType) {
        return Object.keys(query).reduce((acc: QueryType, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
      }
      // afterQRScan() {
      //   if (e.key === 'x-admin-oauth-code') {
      //     const code = getQueryObject(e.newValue)
      //     const codeMap = {
      //       wechat: 'code',
      //       tencent: 'code'
      //     }
      //     const type = codeMap[this.auth_type]
      //     const codeName = code[type]
      //     if (codeName) {
      //       store.user().LoginByThirdparty(codeName).then(() => {
      //         this.$router.push({ path: this.redirect || '/' })
      //       })
      //     } else {
      //       alert('第三方登录失败')
      //     }
      //   }
      // }
    }
  });
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
  @keyframes float {
    0% {
      transform: translateY(0);
    }

    50% {
      transform: translateY(-20px);
    }

    to {
      transform: translateY(0);
    }
  }
  $bg: #283443;
  $light_gray: #333;
  $cursor: #333;
  .login-container {
    display: flex;
    flex-direction: row;
    height: 100vh;
    background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);
    .login-left {
      width: 60%;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      .left-title {
        font-size: 28px;
        color: #333;
        font-weight: bold;
      }
      .left-icon {
        width: 30%;
        animation: float 5s linear 0s infinite;
      }
    }
    .login-right {
      flex: 1;
      background: #fff;
      box-shadow: 0 0 10px #dfdfdf;
      position: relative;
      .title-container {
        padding: 150px 0 0 100px;
        .c-title {
          font-size: 36px;
          font-weight: bold;
        }
        .c-dection {
          font-size: 14px;
          color: #666;
          padding-top: 10px;
        }
      }
      .right-main {
        padding: 40px 150px 0 100px;
      }
      .copy {
        position: absolute;
        bottom: 20px;
        color: #999;
        font-size: 14px;
        width: 100%;
        text-align: center;
        z-index: 3;
      }
    }
  }
</style>
